package com.example.AgentMainTest;

import com.sun.tools.attach.*;

import java.io.IOException;
import java.util.List;
import java.util.Scanner;

/**
 * @author dingrz
 * @date 2022-01-22
 */
public class Test {
    public static void main(String[] args) {
        System.out.println("类加载器："+Test.class.getClassLoader().getClass());
        //获取当前系统运行的jvm进程
        List<VirtualMachineDescriptor> jps = VirtualMachine.list();
        for (int i = 0; i < jps.size(); i++) {
            System.out.println("["+i+"]\t"+ jps.get(i).id() +"\t" + jps.get(i).displayName());
        }
        System.out.print("请输入要增强的进程序号:\n");
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        System.out.println(s);
        VirtualMachineDescriptor virtualMachineDescriptor = jps.get(Integer.valueOf(s));
        try {
            //连接到用户输入的进程44
            System.out.println(String.format("要挂载的进程id:%s, 进程名称:%s",virtualMachineDescriptor.id(),virtualMachineDescriptor.displayName()));
            //附加到到目标虚拟机
            VirtualMachine virtualMachine = VirtualMachine.attach(virtualMachineDescriptor.id());
            //加载agent程序
            virtualMachine.loadAgent("D:\\learning\\agentDemo\\agentMainDemo\\target\\agentMainDemo-1.0-SNAPSHOT.jar","hello");
            //当前程序与目标虚拟机断开连接
            virtualMachine.detach();
        } catch (AttachNotSupportedException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } catch (AgentLoadException e) {
            System.out.println(e.getMessage());
        } catch (AgentInitializationException e) {
            System.out.println(e.getMessage());
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}
